<template>
  <div class="app-container">
    <el-input
      class="marginRB10"
      v-model="listQuery.menu_id"
      placeholder="请输入菜单编号"
      style="width:200px;"
      clearable
    ></el-input>

    <el-input
      v-model="listQuery.pms_name"
      style="width:200px;"
      placeholder="请输入权限名称"
      clearable
    ></el-input>

    <el-button
      class="marginRB10"
      type="primary"
      @click="searchForm"
      icon="el-icon-search"
      >搜索
    </el-button>

    <el-button
      class="marginRB10"
      type="primary"
      icon="el-icon-plus"
      @click="handleCreate()"
    >
      添加
    </el-button>
    <!-- <el-button class="marginRB10" type="primary" @click="cache()">
      缓存权限数据</el-button
    > -->

    <el-table
      :data="menuList"
      style="margin-bottom: 20px;"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="permission_id"
        label="权限ID"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="permission_name"
        label="权限名称"
      ></el-table-column>
      <el-table-column
        prop="permission_key"
        label="权限key值"
        width="450"
      ></el-table-column>
      <el-table-column prop="method" label="请求方法">
        <template slot-scope="{ row }">
          <el-tag :type="row.method | getMethodType">{{ row.method }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="menu_id" label="菜单编号"></el-table-column>
      <el-table-column prop="menu_name" label="菜单名称"></el-table-column>
      <el-table-column prop="add_time" label="添加时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            plain
          >
            编辑
          </el-button>
          <!--          <cus-del-btn @ok="handleDelete(scope.row)"></cus-del-btn>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <cus-pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.perPage"
      @pagination="getList"
    />

    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="right"
        label-width="120px"
        style="width: 600px; margin: 0 auto;"
      >
        <el-form-item label="权限名称">
          <el-input
            v-model="form.permission_name"
            placeholder="请输入权限名称"
          />
        </el-form-item>
        <el-form-item label="操作权限key值" prop="permission_key">
          <el-cascader
            class="cascader"
            v-model="form.permission_key"
            clearable
            filterable
            :options="routes"
            :show-all-levels="false"
            :props="{ expandTrigger: 'hover', value: 'uri', label: 'uri' }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="请求类型" prop="method">
          <el-select filterable v-model="form.method">
            <el-option
              v-for="item in methodOptions"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级菜单ID" prop="menu_id">
          <el-input
            v-model="form.menu_id"
            placeholder="请从下面选择二级菜单ID"
            disabled
            style="margin-bottom: 10px;"
          />
          <el-tree
            :data="menuListData"
            :props="defaultProps"
            @node-click="handleNodeClick"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoutes,
  permissionMenu,
  getMenu,
  saveMenu,
  updateMenu,
  cacheMenu
} from "@/api/config/authentication";

import treeTable from "@/components/TreeTable";
import { validateCh } from "@/utils/validate";

// 常量title
const tempDesc = {
  id: "",
  parentId: "",
  menu_key: "菜单key值",
  menu_name: "名称",
  level: "排序",
  icon: "图标",
  type: "类型",
  status: "状态",
  parentName: "上级菜单"
};

import { METHODS } from "../../data/basic_data";

export default {
  components: { treeTable },
  data() {
    const _validateCh = (rule, value, callback) => {
      if (!!value && validateCh(value)) {
        callback(new Error("不能包含中文"));
      }
      callback();
    };
    return {
      routes: [],

      methodOptions: [
        { value: "post" },
        { value: "put" },
        { value: "get" },
        { value: "delete" }
      ],
      expandAll: false,
      // expandAll: true, // 是否全部展开
      expandAllTitle: "展开全部",
      tempDesc: tempDesc,
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10,
        menu_id: undefined,
        /* 权限搜索字段 */
        pms_name: ""
      },
      defaultProps: {
        children: "children",
        label: "menu_name"
      },
      columns: [
        {
          label: "菜单名称",
          key: "title",
          width: 220,
          expand: true,
          align: "left",
          headerAlign: "center"
        },
        {
          label: "菜单key值",
          key: "menu_key"
        },
        {
          label: tempDesc.type,
          key: "type"
        },
        {
          label: "状态",
          key: "status"
        },
        {
          label: tempDesc.icon,
          key: "icon"
        },
        {
          label: "菜单层级",
          key: "level"
        }
      ],
      menuList: [],
      menuTree: [], // 树形菜单
      menuListData: [], // 树形菜单
      dialogFormVisible: false,
      dialogStatus: "",
      titleMap: {
        update: "编辑",
        create: "增加"
      },
      form: {
        permission_id: undefined,
        permission_name: undefined,
        permission_key: undefined,
        menu_id: undefined,
        method: undefined
      },

      rules: {
        permission_name: [
          { required: true, message: "请输入", trigger: "blur" }
        ],
        permission_key: [
          { required: true, message: "请输入", trigger: "blur" }
        ],
        method: [{ required: true, message: "请选择", trigger: "change" }],
        menu_id: [{ required: true, message: "请输入", trigger: "blur" }]
      }
    };
  },
  filters: {
    getMethodType(value) {
      switch (value) {
        case METHODS.GET:
          return "";
        case METHODS.POST:
          return "info";
        case METHODS.DELETE:
          return "danger";
        case METHODS.PUT:
          return "warning";
      }
    }
  },
  created() {
    // if (this.global_checkBtnPermission(['sys:menu:add', 'sys:menu:addsub', 'sys:menu:edit', 'sys:menu:delete'])) {
    //   this.columns.push({label: '操作', key: 'operation', width: 320})
    // }
    this.getList();
    this.getMenu();
    this.handleRoutes();
  },
  methods: {
    getList() {
      this.listLoading = true;
      let urlData = "?";
      if (this.listQuery.page) urlData += `page=${this.listQuery.page}`;
      if (this.listQuery.perPage)
        urlData += `&perPage=${this.listQuery.perPage}`;
      if (this.listQuery.menu_id)
        urlData += `&menu_id=${this.listQuery.menu_id}`;
      if (this.listQuery.pms_name)
        urlData += `&pms_name=${this.listQuery.pms_name}`;

      permissionMenu(urlData).then(response => {
        this.menuList = response.data.list;
        this.total = response.data.meta.total;
        this.listLoading = false;
      });
    },
    handleRoutes() {
      getRoutes().then(res => {
        let arr = [];
        for (let key in res.data) {
          arr.push({ uri: key, children: [...res.data[key]] });
        }
        this.routes = arr;
      });
    },
    handleChange(value) {
      this.routes.forEach(item => {
        if (item.uri === value[0]) {
          item.children.forEach(i => {
            if (i.uri === value[1]) {
              this.form.method = i.method;
            }
          });
        }
      });
    },

    getMenu() {
      getMenu().then(response => {
        this.menuListData = response.data;
      });
    },
    handleNodeClick(data) {
      this.form.menu_id = data.menu_id;
    },
    handleCreate(row) {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;

      if (!row) {
        // 一级菜单
        this.form.level = "1"; // 默认一级菜单
        this.form.parentId = "0";
      }
      if (row) {
        // 子菜单
        this.form.level = parseInt(row.level) + 1;
        this.form.parentId = row.id;
        this.form.parentName = row.menu_name;
      }
    },
    handleUpdate(row) {
      this.form = [];
      this.form.permission_id = row.permission_id;
      this.form.permission_name = row.permission_name;
      this.form.permission_key = row.permission_key;
      this.form.method = row.method;
      this.form.menu_id = row.menu_id;

      this.dialogStatus = "update";
      this.dialogFormVisible = true;

      let parentNode = this.findTreeNode(row.parentId);
      if (parentNode) {
        this.form.parentName = parentNode.menu_name;
      }

      this.form = Object.assign({}, this.form);
    },
    handleDelete(row) {
      deleteMenu(row.id).then(response => {
        if (response.code === 0) {
          this.getList();
          // this.submitOk(response.message)
          this.$notify({
            type: "success",
            message: "操作成功",
            position: "bottom-right",
            showClose: false,
            duration: 3000
          });
        } else {
          // this.submitFail(response.message)
          this.$message({
            message: response.message,
            type: "error"
          });
        }
      });
    },
    searchForm() {
      this.listQuery.page = 1;
      this.getList();
    },
    submitForm() {
      this.$refs["dataForm"].validate(valid => {
        /* bug  ->  取权限列表的最后一个 */
        if (valid && this.dialogStatus === "create") {
          let tempForm = JSON.parse(JSON.stringify(this.form));
          saveMenu({
            ...tempForm,
            permission_key: tempForm["permission_key"].pop()
          }).then(response => {
            if (response.code === 200) {
              this.getList();
              // this.submitOk(response.message)
              this.$notify({
                type: "success",
                message: "操作成功",
                position: "bottom-right",
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false;
            } else {
              // this.submitFail(response.message)
              this.$message({
                message: response.message,
                type: "error"
              });
            }
          });
        } else if (valid && this.dialogStatus === "update") {
          let tempForm = JSON.parse(JSON.stringify(this.form));
          if (this.form["permission_key"] instanceof Array) {
            tempForm["permission_key"] = tempForm["permission_key"].pop();
          }
          updateMenu(tempForm).then(response => {
            if (response.code === 200) {
              this.getList();
              // this.submitOk(response.message)
              this.$notify({
                type: "success",
                message: "操作成功",
                position: "bottom-right",
                showClose: false,
                duration: 3000
              });
              this.dialogFormVisible = false;
            } else {
              // this.submitFail(response.message)
              this.$message({
                message: response.message,
                type: "error"
              });
            }
          });
        }
      });
    },
    cache() {
      cacheMenu(this.form).then(response => {
        // this.submitOk(response.message)
        this.$notify({
          type: "success",
          message: "操作成功",
          position: "bottom-right",
          showClose: false,
          duration: 3000
        });
      });
    },
    findTreeNode(id) {
      let node = this._.find(this.menuList, { id: parseInt(id) });
      return node;
    },
    handleExpand() {
      this.expandAll = !this.expandAll;
      this.expandAllTitle = this.expandAll ? "折叠全部" : "展开全部";
    },
    resetForm() {
      this.form = {
        permission_id: undefined,
        permission_name: undefined,
        permission_key: undefined,
        menu_id: undefined,
        method: undefined
      };
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs["dataForm"]) {
        this.$refs["dataForm"].clearValidate(); // 清除整个表单的校验
      }
    }
  }
};
</script>

<style scoped>
::v-deep .el-cascader .el-input {
  width: 480px;
}

::v-deep .el-cascader-menu {
  height: 400px;
}
</style>
